package com.will.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.will.server.mapper.CardMapper;
import com.will.server.pojo.Card;
import com.will.server.util.GsonUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/card")
public class CardController {
    /**
     * Auther sun
     * DATE 2023/1/26 15:39
     * VERSION 1.0
     */

    private static final Logger logger = LoggerFactory.getLogger(CardController.class);

    @Autowired
    CardMapper cardMapper;

    @Autowired
    COSClient cosClient;

    @Value("${jwt.salt}")
    String secret;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/checkCard")
    public Map<Object, Object> checkCard() {
        Map<Object, Object> res = new HashMap<>();
        Gson gson = new Gson();
        Set<String> keys = redisTemplate.keys("cards:*");
        int i = 0;
        for(String key : keys) {
            i++;
            String json = (String)redisTemplate.opsForValue().get(key);
            Map map = gson.fromJson(json, Map.class);
            res.put("key" + i, map);
        }
        return res;
    }

    //先改数据库还是redis
    @PostMapping("/cardsPopular")
    public String cardsPopular(@RequestBody String json) {
        Map map = GsonUtils.fromJson(json, Map.class);
        Double cardid = (Double)map.get("cardid");
        long id = cardid.longValue();
        QueryWrapper<Card> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Card card = cardMapper.selectById(id);
        Integer hot = card.getHot();
        hot++;
        card.setHot(hot);
        cardMapper.update(card, queryWrapper);
        redisTemplate.opsForValue().set("cards:"+id, card);
        return "success";
    }

    @PostMapping("/addCardsChat")
    public String updateCardsChat(@RequestBody String json) {
        Map map = GsonUtils.fromJson(json, Map.class);
        String key = (String) map.get("key");
        return null;

    }

    @PostMapping("/getCards")
    public Map<Object, Object> getCard(@RequestBody String json){
        Gson gson = new Gson();
        Map<Object, Object> res = new HashMap<>();
        Map map = null;
        Set<String> keys = redisTemplate.keys("cards:*");
        int i = 0;
        for(String key : keys) {
            i++;
            String mapJson = (String)redisTemplate.opsForValue().get(key);
            map = gson.fromJson(mapJson, Map.class);
            res.put("key" + i, map);
        }
        return res;

    }

    @PostMapping("/checkCard")
    public String addressCards(@RequestBody String json) {
        return null;
    }

    /**
     * 上传
     * @param json
     * @return
     */
    @PostMapping("/uploadCard")
    public String uploadPicture(@RequestBody String json) {
        Gson gson = new Gson();
        Map map = gson.fromJson(json, Map.class);
        String openid = (String)map.get("openid");
        Double latitude = (Double)map.get("latitude");
        Double longitude = (Double)map.get("longitude");
        String classify = (String)map.get("classify");
        String name = (String)map.get("name");
        String fileName = (String)map.get("picName");
        String picBase64 = (String)map.get("picture");
        String picType = (String)map.get("picType");
        String introduce = (String)map.get("introduce");

        //上传图片
        byte[] picBytes = Base64.decodeBase64(picBase64);
        String filePath = getFilePath(fileName);
        try {
            // 目录结构：head-image/2018/12/29/xxxx.jpg
            InputStream inputStream = new ByteArrayInputStream(picBytes);
            uploadImage(filePath, inputStream);
            inputStream.close();
        } catch (Exception e) {
            //上传失败
            e.printStackTrace();
        }

        //生成卡片信息存入MySQL and Redis
        Card card = new Card();
        card.setOpenid(openid);
        card.setClassify(classify);
        card.setName(name);//卡片名
        card.setLatitude(latitude);
        card.setLongitude(longitude);
        card.setPicName(fileName);//文件名
        card.setPicUrl("https://dongdongqiang-1314435838.cos.ap-shanghai.myqcloud.com/" + filePath);
        card.setIntroduce(introduce);
        card.setHot(0);
        card.setScore(0);
        card.setCharList("");
        Long insert = Integer.toUnsignedLong(cardMapper.insert(card));
        card.setId(insert);
        redisTemplate.opsForValue().set("cards:"+insert, gson.toJson(card));

        return "uploadsuccess";

    }

    private void uploadImage(String filePath, InputStream inputStream) {
        // 存储桶的命名格式为 BucketName-APPID，此处填写的存储桶名称必须为此格式
        String bucketName = "dongdongqiang-1314435838";

        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            int available = inputStream.available();
            // 上传的流如果能够获取准确的流长度，则推荐一定填写 content-length
            // 如果确实没办法获取到，则下面这行可以省略，但同时高级接口也没办法使用分块上传了
            objectMetadata.setContentLength(available);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream, objectMetadata);
        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        } catch (CosServiceException e) {
            e.printStackTrace();
        }
    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "物语/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/"
                + System.currentTimeMillis()
                + RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
